package com.pet.controller.webUser;

import com.aliyun.oss.model.GenericRequest;
import com.pet.constant.MessageConstant;
import com.pet.controller.AI.sparkAI.SparkAiWebSocket;
import com.pet.result.Result;
import com.pet.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URL;
import java.util.UUID;

@RestController
@Slf4j
@RequestMapping("/user")
public class CommonController {

    @Autowired
    private AliOssUtil aliOssUtil;
    @Autowired
    private SparkAiWebSocket sparkAiWebSocket;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public Result<String> upload(MultipartFile file){
        log.info("文件上传：{}",file);
        
        try {
            //原始文件名
            String originalFileName = file.getOriginalFilename();
            //截取原始文件名的后缀
            String extension = originalFileName.substring(originalFileName.lastIndexOf("."));
            //构造新文件的名称 随机UUID加文件名
            String objectName = UUID.randomUUID().toString() + extension;

            //文件的请求路径
            String filePath = aliOssUtil.upload(file.getBytes(), objectName);
            return Result.success(filePath);
        } catch (IOException e) {
            log.error("文件上传失败：{}",e);
        }
        return Result.error(MessageConstant.UPLOAD_FAILED);
    }

    /**
     * 删除文件
     */
    @PostMapping("/deleteOssFile")
    public Result<String> deleteOssFile(@RequestParam String fileUrl){
        String handleFIleUrl;
        try {
            URL url = new URL(fileUrl);
            String path = url.getPath();
            // 移除路径开头的斜杠并返回最后一部分
            handleFIleUrl = path.substring(path.lastIndexOf('/') + 1);
        } catch (Exception e) {
            throw new RuntimeException("无效的URL格式", e);
        }
        log.info("删除文件：{},处理后url：{}",fileUrl,handleFIleUrl);
        return Result.success(aliOssUtil.deleteOssFile(handleFIleUrl));
    }

    /**
     * 获取websocketUrl
     */
    @GetMapping("/getWebSocketUrl")
    public Result<String> getWebSocketUrl() throws Exception {
        log.info("获取websocketUrl");
        String websocketUrl = sparkAiWebSocket.getAuthUrl();
        return Result.success(websocketUrl);
    }

    /**
     * 获取websocketUrl-lite
     */
    @GetMapping("/getWebSocketLiteUrl")
    public Result<String> getWebSocketLiteUrl() throws Exception {
        log.info("获取websocketUrl");
        String websocketUrl = sparkAiWebSocket.getWebsocketLiteUrl();
        return Result.success(websocketUrl);
    }
}
